/**
 * @function 获取uuid
 * @return {string} 返回uuid
 **/
 export const getUuid = () => {
	  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
		 return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
	   })
 }

// 实现rich-text富文本中图片宽度最大100%
export function formatContent(html) {
	// 去掉img标签里的style、width、height属性
	let content_data = html.replace(/<img[^>]*>/gi, function(match, capture) {
		match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
		match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
		match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
		return match;
	}); 
	// 修改所有style里的width属性为max-width:100%
	content_data = content_data.replace(/style="[^"]+"/gi, function(match, capture) {
		match = match.replace(/width:[^;]+;/gi, 'max-width:100%;').replace(/width:[^;]+;/gi, 'max-width:100%;');
		return match;
	}); 
	// 去掉<br/>标签
	content_data = content_data.replace(/<br[^>]*\/>/gi, ''); 
	// img标签添加style属性：max-width:100%;height:auto
	content_data = content_data.replace(/\<img/gi,
		'<img style="max-width:100%;height:auto;display:block;margin:0px auto;"');
	return content_data;
}

/**
 * @function 保存图片
 * @param {string} url 下载地址
**/
export const downloadFile = (url, type='img') => {
	if (!url) {
		return uni.$showTost('请传入下载地址！')
	}
	url = url.replace(/http:\/\//g, 'https://')
	uni.showLoading({
		title: '保存中...',
		mask: true
	})
	uni.downloadFile({
		url: url,
		success: async (res) => {
			if (type==='img') {
				uni.saveImageToPhotosAlbum({
					filePath:  res.tempFilePath,
					success: () => {
						uni.$showTost('保存成功！')
					},
					fail: (err) => {
						uni.$showTost('保存失败，请手动截屏保存！')
					},
					complete: () => {
						uni.hideLoading()
					}
				})
			} else {
				await uni.$showTost('即将打开文件，点击文件预览下拉保存文件！', 2000)
				uni.openDocument({
					filePath: res.tempFilePath,
					fileType: 'pdf',
					complete: () => {
						uni.hideLoading()
					},
					fail:() => {
						uni.setClipboardData({
							data: url,
							success: () => {
								uni.$showTost('已复制到系统剪切板，请前往浏览器进行下载')
							}
						})
					}
				})
			}
			
		},
		fail: err => {
			uni.hideLoading()
			uni.$showTost('保存失败')
		}
	})
}